<template>
  <div class="user-management-container">
    <h1>用户管理</h1>
    
    <div class="actions-bar">
      <button class="refresh-btn" @click="fetchUsers" :disabled="isLoading">
        <span class="refresh-icon" :class="{ 'spinning': isLoading }">🔄</span>
        刷新列表
      </button>
      <div class="user-count">
        共 {{ users.length }} 位用户
      </div>
    </div>
    
    <div class="users-table-container">
      <table class="users-table" v-if="users.length > 0">
        <thead>
          <tr>
            <th>ID</th>
            <th>姓名</th>
            <th>注册时间</th>
            <th>最后登录</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in users" :key="user.id" class="user-row">
            <td class="user-id">{{ user.id }}</td>
            <td class="user-name">{{ user.name }}</td>
            <td class="user-created">{{ formatDate(user.created_at) }}</td>
            <td class="user-last-login">
              {{ user.last_login ? formatDate(user.last_login) : '从未登录' }}
            </td>
            <td class="user-actions">
              <button 
                class="delete-btn" 
                @click="confirmDelete(user)"
                :disabled="isDeleting.includes(user.id)"
              >
                {{ isDeleting.includes(user.id) ? '删除中...' : '删除' }}
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      
      <div v-else-if="!isLoading" class="empty-state">
        <div class="empty-icon">👥</div>
        <h3>暂无注册用户</h3>
        <p>请先前往<a href="/register" class="link">人脸注册</a>页面添加用户</p>
      </div>
      
      <div v-else class="loading-state">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
    </div>
    
    <div v-if="message" class="message" :class="messageType">
      {{ message }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

const users = ref([])
const isLoading = ref(false)
const isDeleting = ref([])
const message = ref('')
const messageType = ref('success')

// 格式化日期时间
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 显示消息
const showMessage = (text, type = 'success') => {
  message.value = text
  messageType.value = type
  
  setTimeout(() => {
    message.value = ''
  }, 3000)
}

// 获取用户列表
const fetchUsers = async () => {
  isLoading.value = true
  const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api'
  
  try {
    const response = await axios.get(`${apiBaseUrl}/users`)
    
    if (response.data.success) {
      users.value = response.data.users || []
    } else {
      showMessage(response.data.error || '获取用户列表失败', 'error')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    showMessage('网络错误，请稍后重试', 'error')
  } finally {
    isLoading.value = false
  }
}

// 确认删除
const confirmDelete = (user) => {
  if (confirm(`确定要删除用户"${user.name}"吗？此操作不可撤销。`)) {
    deleteUser(user.id)
  }
}

// 删除用户
const deleteUser = async (userId) => {
  isDeleting.value.push(userId)
  const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api'
  
  try {
    const response = await axios.delete(`${apiBaseUrl}/users/${userId}`)
    
    if (response.data.success) {
      // 从列表中移除用户
      users.value = users.value.filter(user => user.id !== userId)
      showMessage('用户删除成功')
    } else {
      showMessage(response.data.error || '删除用户失败', 'error')
    }
  } catch (error) {
    console.error('删除用户失败:', error)
    showMessage('网络错误，请稍后重试', 'error')
  } finally {
    // 移除删除中的标记
    isDeleting.value = isDeleting.value.filter(id => id !== userId)
  }
}

// 组件挂载时获取用户列表
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-management-container {
  padding: 2rem;
  max-width: 1000px;
  margin: 0 auto;
}

.user-management-container h1 {
  text-align: center;
  margin-bottom: 2rem;
  color: #333;
}

.actions-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.refresh-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.6rem 1rem;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 0.95rem;
  transition: background-color 0.3s ease;
}

.refresh-btn:hover:not(:disabled) {
  background: #1976D2;
}

.refresh-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.refresh-icon {
  font-size: 1rem;
  display: inline-block;
}

.refresh-icon.spinning {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.user-count {
  color: #666;
  font-size: 0.95rem;
}

.users-table-container {
  background: white;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.users-table {
  width: 100%;
  border-collapse: collapse;
}

.users-table th,
.users-table td {
  padding: 1rem;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.users-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.user-row:hover {
  background: #f8f9fa;
}

.user-id {
  font-weight: 500;
  color: #666;
  width: 80px;
}

.user-name {
  font-weight: 500;
  color: #333;
}

.user-created,
.user-last-login {
  color: #666;
  font-size: 0.9rem;
}

.delete-btn {
  padding: 0.4rem 0.8rem;
  background: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.3s ease;
}

.delete-btn:hover:not(:disabled) {
  background: #d32f2f;
}

.delete-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.empty-state {
  padding: 4rem 2rem;
  text-align: center;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
}

.empty-state h3 {
  margin-bottom: 0.5rem;
  color: #333;
}

.empty-state p {
  color: #666;
}

.link {
  color: #2196F3;
  text-decoration: none;
}

.link:hover {
  text-decoration: underline;
}

.loading-state {
  padding: 4rem 2rem;
  text-align: center;
  color: #666;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #2196F3;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 1rem;
}

.message {
  margin-top: 1.5rem;
  padding: 0.8rem;
  border-radius: 5px;
  text-align: center;
}

.message.success {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.message.error {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

@media (max-width: 768px) {
  .user-management-container {
    padding: 1rem;
  }
  
  .actions-bar {
    flex-direction: column;
    align-items: stretch;
    gap: 1rem;
  }
  
  .users-table {
    font-size: 0.9rem;
  }
  
  .users-table th,
  .users-table td {
    padding: 0.8rem 0.5rem;
  }
  
  .user-actions {
    text-align: center;
  }
  
  .delete-btn {
    width: 100%;
  }
}
</style>